﻿using Reopsitroy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Reopsitory
{
    public class BaseRepsitory<TEntity> : IBaseRepsitory<TEntity>
        where TEntity : class
    {
        protected MsDbContext db;

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TEntity Insert(TEntity entity)
        {
            db.Set<TEntity>().Add(entity);
            db.SaveChanges();
            return entity;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Delete(int id)
        {
            var data = db.Set<TEntity>().Find(id);
            db.Set<TEntity>().Remove(data);
            return db.SaveChanges();
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public int DeleteAll(int[] idList)
        {
            foreach(var item in idList)
            {
                db.Set<TEntity>().Find(item);
            }
            return db.SaveChanges();
        }

        /// <summary>
        /// IQueryable查询全部
        /// </summary>
        /// <returns></returns>
        public IQueryable<TEntity> Queryable()
        {
            var list = db.Set<TEntity>();
            return list;
        }

        /// <summary>
        /// List查询全部
        /// </summary>
        /// <returns></returns>
        public List<TEntity> QueryList()
        {
            var list = db.Set<TEntity>().ToList();
            return list;
        }

        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public List<TEntity> QueryList(Expression<Func<TEntity,bool>> condition)
        {
            var list = db.Set<TEntity>().Where(condition).ToList();
            return list;
        }

        /// <summary>
        /// 单个查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>         
        public TEntity QueryFirst(int id)
        {
            return db.Set<TEntity>().Find(id);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public TEntity Update(TEntity entity)
        {
            db.Set<TEntity>().Update(entity);
            db.SaveChanges();
            return entity;
        }
    }
}
